import {Component, HostListener, Input, OnInit} from '@angular/core';
import {errorSnackBar, openSnackBar} from '../../util/snack.util';
import {User} from '../../model/user';
import {AuthService} from '../../service/auth.service';
import {MatSnackBar} from '@angular/material';
import {avatarAnim} from '../../anim/avatar.anim';
import {UserService} from '../../service/user.service';
import {removeUser} from '../../util/app.util';

@Component({
  selector: 'app-avatar',
  templateUrl: './avatar.component.html',
  styleUrls: ['./avatar.component.css'],
  animations: [avatarAnim]
})
export class AvatarComponent implements OnInit {
  @Input()
  user: User;
  avatarState = 'out';

  @HostListener('mouseenter')
  onUserHeadMouseEnter() {
    this.avatarState = 'hover';
  }

  @HostListener('mouseleave')
  onUserHeadMouseLeave() {
    this.avatarState = 'out';
  }

  constructor(
    private snackBar: MatSnackBar,
    private authService: AuthService, public userService: UserService) {
  }

  ngOnInit() {
  }

  logout() {
    this.userService.user = null;
    removeUser();
    if (this.user) {
      this.authService.logout(this.user.token).subscribe(() => {
        this.userService.userChangeEvent.emit(null);
      }, error1 => {
        errorSnackBar(this.snackBar, error1);
      });
    } else {
      openSnackBar(this.snackBar, 'token错误');
    }
  }
}
